package com.meatball.iot.common.mqtt

import com.meatball.iot.common.mqtt.properties.MqttProperties
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component

/**
 * TODO MQTT接收
 *
 * @property mqttProperties
 */
@Component
class IMqttComponent(
    private val mqttProperties: MqttProperties
) {
    companion object {
        private val logger = LoggerFactory.getLogger(IMqttComponent::class.java)
    }

    /**
     * TODO 启动mqtt
     *
     */
    fun startMqtt() {
        val broker = "tcp://${mqttProperties.host}:${mqttProperties.port}"
        val persistence = MemoryPersistence()

        val mqttClient = MqttClient(broker, mqttProperties.clientId, persistence)

        // MQTT连接选项
        val connOpts = MqttConnectOptions().apply {
            userName = mqttProperties.username
            password = mqttProperties.password.toCharArray()
            isCleanSession = false
        }

        // 设置回调
        mqttClient.setCallback(PushCallback())

        // 建立连接
        logger.info("MQTT正在连接到代理服务器broker：$broker。")
        mqttClient.connect(connOpts)
        logger.info("MQTT连接成功。")

        // 订阅主题
        mqttProperties.inboundTopics.forEach {
            mqttClient.subscribe(it.trim())
            logger.info("订阅 $it 成功。")
        }
    }
}